﻿using DotSpatial.Controls;
using DotSpatial.Data;
using DotSpatial.Symbology;
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace DotSpatialExcelAddIn
{
  
    
    public partial class frmSelectActiveSheet : Form
    {
        kUtilityFunction util = new kUtilityFunction();
 
        Map map1;

        public Map Map1
        {
            get { return map1; }
            set { map1 = value; }
        }
        public int SelectedSheet
        {
            get { return cmbSheet.SelectedIndex ;}
            set {}
        }
        
        public frmSelectActiveSheet()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            string url = "http://hydrodata.info/ghcn/cuahsi_1_1.asmx";
            string site = "GHCN:USC00422257";
            string variable = "GHCN:8";
            string StartDate = "2000-06-13T00:00:00";
            string EndDate = "2014-06-13T00:00:00";
            string Keyword = "";
            string VarName = "";
            try
            {
                int iLyr = util.getLayerHdl(cmbLayer.Text, Map1);
                if (iLyr != -1)
                {
                    IFeatureSet FeLyr = Map1.Layers[iLyr].DataSet as IFeatureSet;
                    int nShp = FeLyr.DataTable.Rows.Count;
                    for (int i = 0; i < nShp; i++)
                    {
                        IFeature iFe = FeLyr.GetFeature(i);
                        object val = iFe.DataRow["SiteName"];
                        string fieldResult = Convert.ToString(val);
                        if (fieldResult==cmbSite.Text)
                        {
                            object val1 = iFe.DataRow["ServiceURL"];
                            string url1 = Convert.ToString(val1);
                            object val2 = iFe.DataRow["SiteCode"];
                            string site1 = Convert.ToString(val2);
                            object val3 = iFe.DataRow["VarCode"];
                            string variable1 = Convert.ToString(val3);

                            object val4 = iFe.DataRow["Keyword"];
                            Keyword = Convert.ToString(val4);
                            object val5 = iFe.DataRow["VarName"];
                            VarName = Convert.ToString(val5);
                            
                            url = url1;
                            site = site1;
                            variable = variable1;
                            //string StartDate = "2000-06-13T00:00:00";
                            //string EndDate = "2014-06-13T00:00:00";
                        }
                    }
                }
            }
            catch { }
            string x = "http://hydrodata.info/ghcn/cuahsi_1_1.asmx";
            string y = "http://" + getBetween(url, "http://", ".asmx") + ".asmx"; 
            //MessageBox.Show(y);
            url = y;
            //return; 
            
            //-----------------------------------------------------------------------------------------
            picGlobe.Visible = true;
            picGlobe.Refresh();
            //string url = "http://hydrodata.info/ghcn/cuahsi_1_1.asmx";
            //string site = "GHCN:USC00422257";
            //string variable = "GHCN:8";
            //string StartDate = "2000-06-13T00:00:00";
            //string EndDate = "2014-06-13T00:00:00";
            HttpWebRequest request = CreateWebRequest(url);
            XmlDocument soapEnvelopeXml = new XmlDocument();
            var soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
            soap += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
            soap += "<soap:Body>";
            soap += "<GetValuesObject xmlns=\"http://www.cuahsi.org/his/1.1/ws/\">";
            soap += "<location>" + site + "</location>";
            soap += "<variable>" + variable + "</variable>";
            soap += "<startDate>" + StartDate + "</startDate>";
            soap += "<endDate>" + EndDate + "</endDate>";
            soap += "<authToken></authToken>";
            soap += "</GetValuesObject>";
            soap += "</soap:Body>";
            soap += "</soap:Envelope>";
            soapEnvelopeXml.LoadXml(soap);

            using (Stream stream = request.GetRequestStream())
            {
                soapEnvelopeXml.Save(stream);
            }

            using (WebResponse response = request.GetResponse())
            {
                using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                {
                    string soapResult = rd.ReadToEnd();
                    textBox1.Text = soapResult;
                }
            }
            picGlobe.Visible = false;
            textBox1.Refresh();  
       //-----------------------------------------------------------------------------------------
            Microsoft.Office.Interop.Excel.Application oXL;
            Microsoft.Office.Interop.Excel.Workbook oWB;
            Microsoft.Office.Interop.Excel.Worksheet oSheet;
            oXL = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
            oXL.Visible = true;
            oWB = (Microsoft.Office.Interop.Excel.Workbook)oXL.ActiveWorkbook;
            oSheet = (Worksheet)oWB.Worksheets[cmbSheet.SelectedIndex + 1];
            oSheet.Select();

            List<string> st = getListBetween(textBox1.Text, "<values>", "</values>");
            dataGridView1.Rows.Clear();
            int ii=1;
            oSheet.Cells[ii, 1] = "Date/Time";
            oSheet.Cells[ii, 2] = Keyword;
           // ii++;
           // oSheet.Cells[ii, 2] = VarName;
            foreach (string s in st)
            {
                string[] s2 = s.Split(',');
                string s3 = s2[0].Replace('"', ' ');
                string s4 = s3.Replace('T', ' ');
                if (s4.Length >= 8)
                {
                    ii++;
                    oSheet.Cells[ii, 1 ] = s4.TrimEnd().TrimStart();// s2[0];
                    oSheet.Cells[ii, 2] = s2[1];

                }
            }
            MessageBox.Show("Data downloaded");  
        //----------------------------------------------------------------------------------------     
        }

        private void frmSelectActiveSheet_Load(object sender, EventArgs e)
        {
            this.TopMost = true; 
            cmbLayer.Items.Clear();  
            for (int i = Map1.Layers.Count - 1; i >= 0; i--)
            {
                string str = Map1.Layers[i].LegendText;
                if (str.Length >= 11)
                {
                    string str2 = str.Substring(0, 11);
                    if (str2.ToUpper() != "Brutile.Web".ToUpper())
                    {
                        cmbLayer.Items.Add(Map1.Layers[i].LegendText);
                    }
                }
                else { cmbLayer.Items.Add(Map1.Layers[i].LegendText); }
               
            }
            


            Microsoft.Office.Interop.Excel.Application oXL;
            Microsoft.Office.Interop.Excel.Workbook oWB;
            Microsoft.Office.Interop.Excel.Worksheet oSheet;
            oXL = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
            oXL.Visible = true;
            oWB = (Microsoft.Office.Interop.Excel.Workbook)oXL.ActiveWorkbook;
            int lastSheet = oWB.Worksheets.Count;

            cmbSheet.Items.Add("New sheet");
            cmbSheet.SelectedIndex = 0;
            for (int i = 1; i <= lastSheet; i++)
            {
                cmbSheet.Items.Add( oWB.Worksheets[i].name);
            }
        }

        public HttpWebRequest CreateWebRequest(string url)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            //HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@"http://dev.nl/Rvl.Demo.TestWcfServiceApplication/SoapWebService.asmx");
            webRequest.Headers.Add(@"SOAP:Action");
            webRequest.ContentType = "text/xml;charset=\"utf-8\"";
            webRequest.Accept = "text/xml";
            webRequest.Method = "POST";
            return webRequest;
        }

        List<string> getListBetween(string strSource, string strStart, string strEnd)
        {
            List<string> st = new List<string>();
            string dat = getBetween(strSource, "<values>", "</values>");
            string[] tokens = dat.Split(new string[] { "</value>" }, StringSplitOptions.None);
            st.Clear();
            foreach (string str in tokens)
            {
                string sDate = getBetween(str, "dateTime=", "timeOffset");
                string[] value = str.Split('>');
                st.Add(sDate + ", " + value[1]);
            }

            return st;
        }

        public static string getBetween(string strSource, string strStart, string strEnd)
        {
            int Start, End;
            if (strSource.Contains(strStart) && strSource.Contains(strEnd))
            {
                Start = strSource.IndexOf(strStart, 0) + strStart.Length;
                End = strSource.IndexOf(strEnd, Start);
                return strSource.Substring(Start, End - Start);
            }
            else
            {
                return "";
            }
        }

        private void cmbLayer_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int iLyr = util.getLayerHdl(cmbLayer.Text, Map1);
                if (iLyr != -1)
                {
                    IFeatureSet FeLyr = Map1.Layers[iLyr].DataSet as IFeatureSet;
                    int nShp = FeLyr.DataTable.Rows.Count;
                    for (int i = 0; i < nShp; i++)
                    {
                        IFeature iFe = FeLyr.GetFeature(i);
                        object val = iFe.DataRow["SiteName"];
                        string fieldResult = Convert.ToString(val);
                        if (fieldResult != "") cmbSite.Items.Add(fieldResult);
                    }
                }
            }
            catch { }
        }

    }
}
